<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="uname">
        <el-input
          v-model="queryParams.uname"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="trueName">
        <el-input
          v-model="queryParams.trueName"
          placeholder="请输入用户真实姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户分组" prop="ucateId">
        <el-select v-model="queryParams.ucateId" placeholder="用户分组" clearable>
          <el-option
            v-for="ucate in ucateList"
            :key="ucate.value"
            :label="ucate.cateName"
            :value="ucate.ucateId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="用户性别" clearable>
          <el-option
            v-for="dict in dict.type.zhhq_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['zhhq:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zhhq:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zhhq:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['zhhq:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="uid" />
      <el-table-column label="用户名" align="center" prop="uname" />
      <el-table-column label="用户真实姓名" align="center" prop="trueName" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zhhq_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="用户生日" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户分类" align="center" prop="usercate.cateName" />
      <el-table-column label="用户手机" align="center" prop="phone" />
      <el-table-column label="在职状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zhhq_zy" :value="scope.row.status" @click.native="handleZH(scope.row)" class="tag"/>
        </template>
      </el-table-column>
      <el-table-column label="若依用户编号" align="center" prop="sysUser.userId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zhhq:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zhhq:user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="uid">
          <el-input v-model="form.uid" placeholder="请输入用户ID" :disabled="isUpdate"/>
        </el-form-item>
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="form.uname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="trueName">
          <el-input v-model="form.trueName" placeholder="请输入用户真实姓名" />
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.zhhq_sex"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户密码" prop="passwd">
          <el-input v-model="form.passwd" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="用户生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择用户生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户分类" prop="ucateId">
          <el-select v-model="form.ucateId" placeholder="用户分组" clearable>
            <el-option
              v-for="ucate in ucateList"
              :key="ucate.value"
              :label="ucate.cateName"
              :value="ucate.ucateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入用户手机" />
        </el-form-item>
<!--        <el-form-item label="在职状态" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in dict.type.zhhq_zy"-->
<!--              :key="dict.value"-->
<!--              :label="dict.value"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/zhhq/user";
import { listUsercate } from '@/api/zhhq/usercate'
import { addUser as addUserSys, updateUser as updateUserSys, delUser as delUserSys } from "@/api/system/user";

export default {
  name: "User",
  dicts: ['zhhq_zy', 'zhhq_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      ucateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isUpdate: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uname: null,
        trueName: null,
        passwd: null,
        sex: null,
        birthday: null,
        ucateId: null,
        phone: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uid: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        uname: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        trueName: [
          { required: true, message: "用户真实姓名不能为空", trigger: "blur" }
        ],
        passwd: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "用户性别不能为空", trigger: "change" }
        ],
        birthday: [
          { required: true, message: "用户生日不能为空", trigger: "blur" }
        ],
        ucateId: [
          { required: true, message: "用户分组不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        console.log(response.rows)
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listUsercate().then(response => {
        this.ucateList = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
        uname: null,
        trueName: null,
        passwd: null,
        sex: '男',
        birthday: null,
        ucateId: null,
        phone: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.uid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate = false
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isUpdate = true
      const uid = row.uid || this.ids
      getUser(uid).then(response => {
        this.form = response.data;
        this.form.sysUser.userId = row.sysUser.userId
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 修改按钮操作 */
    handleZH(row) {
      this.reset();
      const uid = row.uid || this.ids
      getUser(uid).then(response => {
        this.form = response.data;
        if (response.data.status === '0') {
          this.form.status = '1'
        } else {
          this.form.status = '0'
        }
        updateUser(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let sex;
          if (this.form.sex === '男') {
            sex = '0'
          } else {
            sex = '1'
          }
          let roleId
          if (this.form.ucateId === '01') {
            roleId = 102
          } else if (this.form.ucateId === '02') {
            roleId = 105
          } else if (this.form.ucateId === '03') {
            roleId = 103
          } else if (this.form.ucateId === '04') {
            roleId = 104
          }
          if (this.isUpdate) {
            updateUser(this.form).then(response => {
              updateUserSys({
                userId: this.form.sysUser.userId,
                userName: this.form.uname,
                nickName: this.form.trueName,
                password: this.form.passwd,
                phonenumber: this.form.phone,
                sex,
                roleIds: [roleId]
              })
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              addUserSys({
                userName: this.form.uname,
                nickName: this.form.trueName,
                password: this.form.passwd,
                phonenumber: this.form.phone,
                sex,
                roleIds: [roleId]
              })
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uids = row.uid || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + uids + '"的数据项？').then(function() {
        return delUser(uids), delUserSys(row.sysUser.userId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zhhq/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.tag {
  cursor: pointer;
}
</style>
